import {Component, OnDestroy, OnInit, ViewEncapsulation} from '@angular/core';
import {FormBuilder, Validators, FormGroup} from '@angular/forms';
import {Router} from '@angular/router';
import {Subscription} from "rxjs";
import {UserActivityService} from "@shared/service/user-activity/user-activity.service";
import {ToolsService} from "@shared/service/tools/tools.service";
import {ToolbarService} from "@shared/components/toolbar/toolbar.service";
import {EventsService} from "@core/events/events.service";
import {ValidationService} from "@shared/service/validator/validator.service";


@Component({
  selector: 'app-set-nickname',
  templateUrl: './set-nickname.component.html',
  styleUrls: ['./set-nickname.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class SetNicknameComponent implements OnInit, OnDestroy {
  nickNameForm: FormGroup;
  subscription: Subscription = new Subscription();
  public checkValid: Boolean = false;
  public msg = '';  // 错误信息
  constructor(public formBuider: FormBuilder,
              public userActivityService: UserActivityService,
              public tools: ToolsService,
              public router: Router,
              public toolBarService: ToolbarService,
              public events: EventsService) {
    this.nickNameForm = this.formBuider.group({
      'nickName': ['', [Validators.required, Validators.minLength(4), Validators.maxLength(20), ValidationService.nickNameValidator]]
    });
    this.events.publish('progressbar:hide');

  }

  ngOnInit() {
    this.subscription.add(
      this.toolBarService.unfoldNav()
    );
    this.subscription.add(
      this.nickNameForm.valueChanges
        .debounceTime(300)
        .distinctUntilChanged()
        .subscribe(res => {
          if (this.nickNameForm.invalid && this.nickNameForm.controls['nickName'].errors['invalidAccount']) {
            this.checkValid = true;
            this.msg = ValidationService.getValidatorErrorMessage('invalidNickname');
          } else {
            this.checkValid = false;
            this.msg = '';
          }
        })
    );
  }

  jump() {
    this.router.navigate(['/home']);
  }

  // 设置昵称
  setNickName() {
    const data = {
      nickName: this.nickNameForm.value.nickName
    };
    this.subscription.add(
      this.userActivityService.setNickname(data).subscribe((res) => {
        if (res.result === '0') {
          this.tools.showToast('注册成功正在跳转至首页...', 1000);
          setTimeout(() => {
            // this.navCtrl.push(LoginPage)
            this.router.navigate(['/']);
          }, 1000);
        } else {
          this.tools.showStatusCodeMsg(res.result);
        }
      })
    );
  }

  goBack() {
    window.history.back();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

}
